package io.jft.doll.tcp.utils

import io.netty.buffer.ByteBuf

/**
 *
 * @author Administrator
 */
object CRC16 {
    /**
     * CRC校验
     * @param data 数据段
     * @param crcCode 数据段里的CrcCode
     * @param start 开始位置
     * @param length 长度
     * @return
     */
    fun crcCal(byteBuf: ByteBuf?, start: Int, length: Int): Int {
        var crcValue = 0xffff
        if (byteBuf != null)
            for (n in 0 until length) {
                crcValue = crcValue xor (byteBuf.getByte(start + n).toInt() and 0x00ff)
                for (i in 0..7) {
                    crcValue = if (crcValue and 0x0001 == 0x0001)
                        crcValue shr 1 xor 0xa001
                    else
                        crcValue shr 1
                }
            }
        return crcValue
    }
}